/********************************************************************************/
/*										*/
/*			     	TPM Bind/Unbind routines			*/
/*			     Written by J. Kravitz				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: bind.c 4089 2010-06-09 00:50:31Z kgoldman $			*/
/*										*/
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* Redistributions in binary form must reproduce the above copyright		*/
/* notice, this list of conditions and the following disclaimer in the		*/
/* documentation and/or other materials provided with the distribution.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT		*/
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR	*/
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT		*/
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,	*/
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT		*/
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,	*/
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY	*/
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT		*/
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE	*/
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.		*/
/********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TCM_POSIX
#include <netinet/in.h>
#endif
#ifdef TCM_WINDOWS
#include <winsock2.h>
#endif
#include <tcm.h>
#include <tcmutil.h>
#include <tcmkeys.h>
#include <tcm_constants.h>
#include <oiaposap.h>
#include <tcmfunc.h>
#include <hmac.h>




uint32_t TSS_SM4Encrypt(       uint32_t keyhandle,
                               unsigned char *keyauth,
                               unsigned char *data, uint32_t datalen,
                               unsigned char *blob, uint32_t *bloblen)
{
    uint32_t ret = 0;
    STACK_TCM_BUFFER(tcmdata)
    session sess;
    unsigned char pubauth[TCM_HASH_SIZE];
    unsigned char IV[16] = {0};
    uint32_t ordinal = htonl(TCM_ORD_SM4Encrypt);
    uint32_t datsize = htonl(datalen);

    uint32_t keyhndl = htonl(keyhandle);
    uint32_t IVlen = 16;
    uint16_t keytype;
    uint32_t infosize;
    unsigned char c = 0;
    /* check input arguments */
    if (data == NULL || blob == NULL) return ERR_NULL_ARG;
    if (keyhandle == 0x40000000) keytype = TCM_ET_SMK;
    else						 keytype = TCM_ET_KEYHANDLE;

    ret = needKeysRoom(keyhandle, 0 , 0, 0          );
    if (ret != 0) {
        return ret;
    }


    memset(IV, 'a', 16);

    /* Open OSAP Session */
    ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP/*|SESSION_DSAP*/, &sess, keyauth, keytype, keyhandle);
    if (ret != 0) {
        return ret;
    }
    ret = TSS_authhmac1(pubauth, TSS_Session_GetAuth(&sess), TCM_HASH_SIZE,
                        TSS_Session_GetSeq(&sess), c,
                        TCM_U32_SIZE, &ordinal,
                        IVlen, IV,
                        TCM_U32_SIZE, &datsize,
                        datalen, data, 0, 0);
    if (ret != 0) {
        TSS_SessionClose(&sess);
        return ret;
    }
    /* build the request buffer */

    ret = TSS_buildbuff("00 C2 T l l % @ L %", &tcmdata,
                        ordinal,
                        keyhndl,
                        IVlen, IV,
                        datalen, data,
                        TSS_Session_GetHandle(&sess),
                        TCM_HASH_SIZE, pubauth);
    if ((ret & ERR_MASK) != 0) {
        TSS_SessionClose(&sess);
        return ret;
    }
    /* transmit the request buffer to the TPM device and read the reply */
    ret = TCM_Transmit(&tcmdata, "SM4Ecrypt- AUTH");


    if (ret != 0) {
        TSS_SessionClose(&sess);
        return ret;
    }
    /* calculate the size of the returned Blob */
    ret = tcm_buffer_load32(&tcmdata, TCM_DATA_OFFSET , &infosize);
    if ((ret & ERR_MASK)) {
		TSS_SessionClose(&sess);
        return ret;
    }
    /* check the HMAC in the response */
    ret = TSS_checkhmac1(&tcmdata, ordinal,
                         TSS_Session_GetSeq(&sess), TSS_Session_GetAuth(&sess), TCM_HASH_SIZE,
                         TCM_U32_SIZE, TCM_DATA_OFFSET ,
                         infosize, TCM_DATA_OFFSET + TCM_U32_SIZE ,
                         0, 0);
    TSS_SessionClose(&sess);
    if (ret != 0) {
        return ret;
    }
    /* copy the returned blob to caller */
	if((int)infosize > (int)*bloblen) return ERR_BUFFER;	
    memcpy(blob, &tcmdata.buffer[TCM_DATA_OFFSET + TCM_U32_SIZE ], infosize);
    *bloblen = infosize;

    return ret;
}


uint32_t TSS_SM4Decrypt(       uint32_t keyhandle,
                               unsigned char *keyauth,
                               unsigned char *data, uint32_t datalen,
                               unsigned char *blob, uint32_t *bloblen)
{
    uint32_t ret = 0;
    STACK_TCM_BUFFER(tcmdata)
    session sess;
    unsigned char pubauth[TCM_HASH_SIZE];
    unsigned char IV[16] = {0};
    uint32_t ordinal = htonl(TCM_ORD_SM4Decrypt);
    uint32_t datsize = htonl(datalen);

    uint32_t keyhndl = htonl(keyhandle);
    uint32_t IVlen = 16;
    uint16_t keytype;
    uint32_t infosize;
    unsigned char c = 0;
    /* check input arguments */
    if (data == NULL || blob == NULL) return ERR_NULL_ARG;
    if (keyhandle == 0x40000000) keytype = TCM_ET_SMK;
    else						 keytype = TCM_ET_KEYHANDLE;

    ret = needKeysRoom(keyhandle, 0 , 0, 0          );
    if (ret != 0) {
        return ret;
    }


    memset(IV, 'a', 16);

    /* Open OSAP Session */
    ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP, &sess, keyauth, keytype, keyhandle);
    if (ret != 0) {
        return ret;
    }
    ret = TSS_authhmac1(pubauth, TSS_Session_GetAuth(&sess), TCM_HASH_SIZE,
                        TSS_Session_GetSeq(&sess), c,
                        TCM_U32_SIZE, &ordinal,
                        IVlen, IV,
                        TCM_U32_SIZE, &datsize,
                        datalen, data, 0, 0);
    if (ret != 0) {
        TSS_SessionClose(&sess);
        return ret;
    }
    /* build the request buffer */

    ret = TSS_buildbuff("00 C2 T l l % @ L %", &tcmdata,
                        ordinal,
                        keyhndl,
                        IVlen, IV,
                        datalen, data,
                        TSS_Session_GetHandle(&sess),
                        TCM_HASH_SIZE, pubauth);
    if ((ret & ERR_MASK) != 0) {
        TSS_SessionClose(&sess);
        return ret;
    }
    /* transmit the request buffer to the TPM device and read the reply */
    ret = TCM_Transmit(&tcmdata, "SM4Decrypt- AUTH");


    if (ret != 0) {
        TSS_SessionClose(&sess);
        return ret;
    }
    /* calculate the size of the returned Blob */
    ret = tcm_buffer_load32(&tcmdata, TCM_DATA_OFFSET , &infosize);
    if ((ret & ERR_MASK)) {
		TSS_SessionClose(&sess);
        return ret;
    }
    /* check the HMAC in the response */
    ret = TSS_checkhmac1(&tcmdata, ordinal,
                         TSS_Session_GetSeq(&sess), TSS_Session_GetAuth(&sess), TCM_HASH_SIZE,
                         TCM_U32_SIZE, TCM_DATA_OFFSET ,
                         infosize, TCM_DATA_OFFSET + TCM_U32_SIZE ,
                         0, 0);
    TSS_SessionClose(&sess);
    if (ret != 0) {
        return ret;
    }
    /* copy the returned blob to caller */
	if((int)infosize > (int)*bloblen) return ERR_BUFFER;	
    memcpy(blob, &tcmdata.buffer[TCM_DATA_OFFSET + TCM_U32_SIZE ], infosize);
    *bloblen = infosize;

    return ret;
}

